package com.onec.service.customer.service.impl;

import com.onec.service.api.dto.request.gateway.BizContent;
import com.onec.service.api.enums.error.MerchantErrorEnum;
import com.onec.service.api.exception.CustomerException;
import com.onec.service.customer.dao.merchant.MerchantBusinessRepository;
import com.onec.service.customer.entity.merchant.MerchantBusiness;
import com.onec.service.customer.entity.merchant.MerchantInfo;
import com.onec.service.customer.service.MerchantBusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;


/**
 * @author onec
 * @see com
 */
@Service
public class MerchantBusinessServiceImpl implements MerchantBusinessService {

    @Autowired
    MerchantBusinessRepository merchantBusinessRepository;

    @Override
    public MerchantBusiness findByMerchantIdBusinessNo(long merchantId, String businessNo) {
        return merchantBusinessRepository.findByBusinessNoAndMerchantId(businessNo, merchantId);
    }

    /**
     * 创建商户业务信息：
     *
     * @param bizContent
     * @param merchantInfo
     * @return merchantBusiness
     */
    @Override
    public MerchantBusiness createMerchantBusiness(BizContent bizContent, MerchantInfo merchantInfo) {
        MerchantBusiness merchantBusiness = findByMerchantIdBusinessNo(merchantInfo.getId(), bizContent.getBusinessNo());
        if (Optional.ofNullable(merchantBusiness).isPresent()) {
            throw new CustomerException(MerchantErrorEnum.PRODUCT_MERCHANT_ERROR_OPEN, bizContent.getBusinessNo());
        }
        merchantBusiness = new MerchantBusiness(bizContent);
        merchantBusiness.setMerchantId(merchantInfo.getId());
        merchantBusiness.setVersion(1);
        merchantBusinessRepository.save(merchantBusiness);
        return merchantBusiness;
    }
}
